package org.devcp.tp.common.websocket;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

public class RoomWebSocketHandshakeInterceptor implements HandshakeInterceptor {
	private static final Logger logger = Logger.getLogger(RoomWebSocketHandshakeInterceptor.class);
	
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object
                > attributes) throws Exception {
    	logger.debug("running beforeHandshake method...");
    	
    	if(request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
    		request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
       }
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            String roomId = servletRequest.getServletRequest().getParameter("roomId");
            attributes.put(Constants.ROOM_ID,roomId);
//            HttpSession session = servletRequest.getServletRequest().getSession(false);
//            if (session != null) {
//                //使用userName区分WebSocketHandler，以便定向发送消息
//                String userName = (String) session.getAttribute("userInfo");
//                attributes.put(Constants.WEBSOCKET_USERNAME,userName);
//            }
        }
        return true;
    }
// 
//    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
 
    }
}

